package com.rlyy.rsj.job.remind;

import com.alibaba.fastjson.JSONObject;
import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.TableNode;
import com.rlyy.rsj.dao.OrgDao2;
import com.rlyy.rsj.dao.OrgpDao2;
import com.rlyy.rsj.entity.UsageRemindEntity;
import com.rlyy.rsj.entity.UsageRemindRedisValue;
import com.rlyy.rsj.job.IScheduler;
import com.rlyy.rsj.utils.DistributeLock;
import com.rlyy.rsj.utils.JSONUtils;
import com.rlyy.rsj.utils.RedisKeyFactory;
import com.rlyy.rsj.utils.RedisUtils;
import common.util.DateTimeFormatterUtil;
import common.util.emailUtils.EmailMessage;
import common.util.emailUtils.EmailUtil;
import common.util.emailUtils.TemplateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.NumberFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import static com.rlyy.rsj.utils.DistributeLock.oneMinute;

/**
 * @author : shibixiao
 * @description :
 * @date : 2021-06-30 09:55
 **/
@Deprecated
@Component
public class TempUsageRemindJob implements IRemindJob, IScheduler{

    @Autowired
    private OrgDao2 orgDao2;

    @Autowired
    private OrgpDao2 orgpDao2;

    private static final String LOCK_KEY = RedisKeyFactory.wrapJobKey(TempUsageRemindJob.class.getName());
    private static final String REMIND_KEY = RedisKeyFactory.wrapJobKey("remind");
    private static final String HEALTH_KEY = RedisKeyFactory.wrapJobKey("remind_health");

    private static final String FROM = "融联易云-融数聚";

    private static final String SUBJECT_TEMP = "融数聚-使用量提醒";

    private static final String MAIL_TEMPLATE = "${receiveUser}：<br>" +
            "&nbsp;&nbsp;&nbsp;&nbsp;您好！<br>" +
            "&nbsp;&nbsp;&nbsp;&nbsp;您的签约客户【${orgName}】于${statisticTime}存在余量不足的合同。" +
            "请您尽快登录<a href='https://rsj.ronglianyiyun.com'>融数聚系统<a/>查询。谢谢！<br>" +
            "&nbsp;&nbsp;&nbsp;&nbsp;详细信息如下：<br>" +
            "&nbsp;&nbsp;&nbsp;&nbsp;合同编号：${orgpId}<br>" +
            "&nbsp;&nbsp;&nbsp;&nbsp;产品名称：${orgpProdName}<br>" +
            "&nbsp;&nbsp;&nbsp;&nbsp;产品编号：${orgpProdUid}<br>" +
            "&nbsp;&nbsp;&nbsp;&nbsp;当前使用百分比：${orgpUsePercent}<br>" +
            "<br>" +
            "&nbsp;&nbsp;&nbsp;&nbsp;此为系统邮件，请勿回复。<br>";

    private static final String DEFAULT_RECEIVE_USER = "张萧匀";

    private static final String DEFAULT_RECEIVE_USER_MAIL = "zhangxiaoyun@ronglianyiyun.com";

    @Override
//    @Scheduled(cron = "0 30 9 * * ?")
    public void scheduler() {
        try {
            String result = DistributeLock.get(LOCK_KEY);
            if (StringUtils.isBlank(result)) {
                DistributeLock.lock(LOCK_KEY, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()), oneMinute);
                logger.info("{}-开始定时任务:{}",LOCAL_INFO, "预警任务");
                //统计存活状态
                RedisUtils.hset(HEALTH_KEY, LOCAL_INFO, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()));
                LocalDateTime now = LocalDateTime.now();
                TableNode allOrgp = orgpDao2.getOrgpByProdUid("RJQ020");  //个人工商
                List<UsageRemindEntity> usageReminds = JSONUtils.TableNode2JavaList(allOrgp, UsageRemindEntity.class);
                for (UsageRemindEntity usage: usageReminds) {
                    usage.setStatisticTime(now);
                    if(this.remindCondition(usage)){
                        this.doRemind(usage);
                    }
                }
                //统计完成状态
                RedisUtils.set(REMIND_KEY, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()), -1);
                DistributeLock.unlock(LOCK_KEY);
            } else {
                logger.warn("{}-未执行预警任务!",LOCAL_INFO);
            }

        } catch (Exception e) {
            logger.error("{}-合同使用量邮件提醒任务执行失败!",LOCAL_INFO, e);
            throw new RuntimeException("合同使用量邮件提醒任务执行失败!", e);
        }
    }




    @Override
    public boolean remindCondition(UsageRemindEntity usageRemindEntity) {
        boolean isRemind;
        double percent = usageRemindEntity.getOrgpUsePercent();
        Map<Object, Object> remind = RedisUtils.hmget(RedisKeyFactory.wrapRemindKey(usageRemindEntity.getOrgpId()));
        if(CollectionUtils.isEmpty(remind)){
            return percent >= 0.8;
        }
        UsageRemindRedisValue remindRedisValue = JSONObject.parseObject(JSONObject.toJSONString(remind),UsageRemindRedisValue.class);
        switch (remindRedisValue.getRemindNumbers()){
            case 1:
                isRemind = percent >= 0.9;
                break;
            case 2:
                isRemind = percent >= 0.95;
                break;
            case 3:
                isRemind = percent >= 1.0;
                break;
            default:
                isRemind = false;
                break;
        }
        return isRemind;
    }


    @Override
    public void doRemind(UsageRemindEntity usageRemindEntity) {

        MapNode orgInfo = orgDao2.getOrgInfo(usageRemindEntity.getOrgId());
        usageRemindEntity.setOrgName(orgInfo.getValue("Org_Name"));
        usageRemindEntity.setReceiveUser(DEFAULT_RECEIVE_USER);
        usageRemindEntity.setReceiveUsermail(DEFAULT_RECEIVE_USER_MAIL);

        EmailMessage message = new EmailMessage();
        String template = StringUtils.isNotBlank(usageRemindEntity.getMailTemplate()) ? usageRemindEntity.getMailTemplate() : MAIL_TEMPLATE;
        message.setContent(parseMailContent(usageRemindEntity,template));
        message.setReceiveMailAccount(usageRemindEntity.getReceiveUsermail());
        message.setFrom(FROM);
        message.setSubject(SUBJECT_TEMP);

        try {
            EmailUtil.sendMail(message);
            logger.info("合同{}使用量达到{}，邮件已发送", usageRemindEntity.getOrgpId(),getPercent(usageRemindEntity.getOrgpUsePercent()));
            // 更新redis
            RedisUtils.hincr(RedisKeyFactory.wrapRemindKey(usageRemindEntity.getOrgpId()),"remindNumbers",1.0);
            RedisUtils.hset(RedisKeyFactory.wrapRemindKey(usageRemindEntity.getOrgpId()),"remindTime", DateTimeFormatterUtil.dateTimeToDate(usageRemindEntity.getStatisticTime()));
        } catch (Exception e) {
            logger.error("邮件发送失败，具体原因：", e);
        }
    }

    private String parseMailContent(UsageRemindEntity usageRemindEntity, String mailTemplate){
        Map<String, Object> params = JSONObject.parseObject(JSONObject.toJSONString(usageRemindEntity), Map.class);
        params.put("orgpUsePercent", getPercent(usageRemindEntity.getOrgpUsePercent()));
        return TemplateUtils.doParseMailTemplate(mailTemplate, params);
    }

    private String getPercent(double d){
        NumberFormat nt = NumberFormat.getPercentInstance();
        //设置百分数保留两位小数
        nt.setMinimumFractionDigits(2);
        String percent = nt.format(d);
        return percent;
    }
}
